package com.coocaa.ops.api.v1.internal.provider.impl;

import com.coocaa.ops.api.base.cache.enums.InterfaceCacheMethodEnum;
import com.coocaa.ops.api.base.cache.model.SimpleCacheKey;
import com.coocaa.ops.api.base.cache.service.SimpleCacheService;
import com.coocaa.ops.api.v1.internal.mapper.IPolicyCacheMapper;
import com.coocaa.ops.api.v1.internal.provider.ICacheUpdateProvider;
import com.coocaa.ops.api.v1.policy.biz.IPolicyBiz;
import com.coocaa.ops.api.v1.policy.model.DeviceInfoModel;
import com.coocaa.ops.common.core.biz.cache.constant.CacheTime;
import com.coocaa.ops.common.core.biz.policygroup.entity.PolicyGroupChipModelConfigEntity;
import com.coocaa.ops.common.core.biz.policygroup.entity.PolicyGroupInfoEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tangminghong
 * @date 2020-08-11
 */
@Service("policyGroup")
public class  PolicyGroupCacheUpdateProviderImpl implements ICacheUpdateProvider {

    @Autowired
    private SimpleCacheService cacheService;

    @Autowired
    private IPolicyCacheMapper policyCacheMapper;

    @Autowired
    private IPolicyBiz policyBiz;

    /**
     * 更新缓存-通过资源ID
     *
     * @param idStr
     * @return 缓存key列表
     */
    @Override
    public List<String> updateCacheByResourceId(String idStr) {
        Integer id = Integer.valueOf(idStr);
        List<PolicyGroupChipModelConfigEntity> deviceList = policyCacheMapper.getDeviceByPolicyIdForLastTwoVersion(id);
        List<String> keyList = new ArrayList<>(deviceList.size());
        SimpleCacheKey cacheKey = SimpleCacheKey.getCacheKeyInstance(InterfaceCacheMethodEnum.getPolicyListByDeviceInfo);
        for (PolicyGroupChipModelConfigEntity device : deviceList) {
            DeviceInfoModel deviceInfoModel = new DeviceInfoModel(device.getChip(), device.getModel());
            List<PolicyGroupInfoEntity> policyList = policyBiz.getPolicyListByDeviceInfo(deviceInfoModel);
            cacheKey.withFilterKey("chip", deviceInfoModel.getChip());
            cacheKey.withFilterKey("model", deviceInfoModel.getModel());
            cacheService.set(cacheKey, policyList, CacheTime.ONE_DAY);
            keyList.add(cacheKey.toString());
        }
        return keyList;
    }
}
